package com.yzs.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yzs.common.bean.R;
import com.yzs.entity.Admin;
import com.yzs.entity.Session;
import com.yzs.mapper.AdminMapper;
import com.yzs.mapper.HouseMapper;
import com.yzs.mapper.SessionMapper;
import com.yzs.service.IDashboardService;
import com.yzs.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DashboardService<T> implements IDashboardService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    SessionMapper sessionMapper;
    @Autowired
    HouseMapper houseMapper;
    @Autowired
    JwtUtil JwtUtil;
    @Override
    public R getPanelData(String token) {
        Integer id = JwtUtil.verifyToken(token);
        if(id > 0){
            HashMap<String, Long> map = new HashMap<>();
            Long personnel = adminMapper.selectCount(null);
            map.put("personnel",personnel);
            QueryWrapper<Session> sessionQueryWrapper = new QueryWrapper<>();
            sessionQueryWrapper.eq("user_id", id);
            Integer unread = 0;
            try{
                unread = sessionMapper.selectOne(sessionQueryWrapper).getUnreadCount();
            }catch (Exception e){
                unread = 0;
            }
            map.put("unread",unread.longValue());
            Long house = houseMapper.selectCount(null);
            map.put("house",house.longValue());
            return R.ok(map);
        }
        return R.error("请重新登录！");
    }

    @Override
    public R getChartData() {
        Map<Integer, Long> personnelData = lineData((BaseMapper<T>) adminMapper);
        Map<Integer, Long> houseData = lineData((BaseMapper<T>) houseMapper);
        HashMap<String, Map<Integer, Long>> map = new HashMap<>();
        map.put("admin",personnelData);
        map.put("house",houseData);
        map.put("order",null);
        return R.ok(map);
    }

    /**
     * 每月分组查询 数据
     * @param mapper
     * @return
     */
    private Map<Integer,Long> lineData(BaseMapper<T> mapper){
        HashMap<Integer, Long> map = new HashMap<>();
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        wrapper.select("MONTH(create_time)","count(*)").groupBy("MONTH(create_time)");
        List<Map<String, Object>> list = mapper.selectMaps(wrapper);
        list.stream().forEach((stringObjectMap -> {
            Integer m = (Integer) stringObjectMap.get("MONTH(create_time)");
            Long n = (Long) stringObjectMap.get("count(*)");
            map.put(m,n);
        }));
        return map;
    }
}
